import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules

df = pd.read_excel('C:/关联规则/餐厅数据.xlsx')
print(df.head)

# 转换菜品格式
transactions = df['菜品'].str.split(',').to_list()

# 标准化
te = TransactionEncoder()
te_ary = te.fit(transactions).transform(transactions)
df_encoded = pd.DataFrame(te_ary, columns=te.columns_)

# print(df_encoded.head())
# 使用apriori进行分析
frequent_itemsets = apriori(df_encoded, min_support=0.1, use_colnames=True)
frequent_itemsets.sort_values(by='support', ascending=False, inplace=True)

# 选择二项集查看
print(frequent_itemsets[frequent_itemsets.itemsets.apply(lambda x: len(x) == 2)])